package cn.edu.cug.utils;

import com.mysql.cj.api.mysqla.result.Resultset;
import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Created by xhhuang on 2017/11/9.
 */
public class DBConnector {
  private static final Logger LOG = LoggerFactory.getLogger(DBConnector.class);
  private String dbDriver; // 使用的驱动
  private String dbUrl; // 数据库连接地址
  private String dbUserName; // 数据库的用户名
  private String dbPasswd; // 数据库的密码
  private String dataBase;// 要选用的数据库名称

  Resource jdbcResour;
  Properties props;

  public DBConnector() throws IOException {
    this.jdbcResour = new ClassPathResource("/dbconfig.properties");
    this.props = PropertiesLoaderUtils.loadProperties(jdbcResour);

    this.dbDriver = props.getProperty("drive");
    this.dbUrl = props.getProperty("url");
    this.dataBase = props.getProperty("database");

    this.dbUserName = props.getProperty("username");
    this.dbPasswd = props.getProperty("passwd");
  }

  public Connection getConnection() throws SQLException {
    BasicDataSource basicDataSource = new BasicDataSource();

    // 设置数据库连接属性
    LOG.info("数据库连接Driver："+dbDriver);
    basicDataSource.setDriverClassName(dbDriver);

    LOG.info("数据库连接地址："+dbUrl+"/"+dataBase+"?useUnicode=true&characterEncoding=utf8");
    basicDataSource.setUrl(dbUrl+"/"+dataBase+"?useUnicode=true&characterEncoding=utf8");

    LOG.info("数据库用户名："+dbUserName);
    basicDataSource.setUsername(dbUserName);

    LOG.info("数据库密码："+dbPasswd);
    basicDataSource.setPassword(dbPasswd);

    Connection connection = basicDataSource.getConnection();

    return connection;
  }

  public ResultSet getSQLResult(Connection connection, String SQLSentence) throws SQLException {
    // SELECT * from match_team
    Statement statement = connection.createStatement();
    ResultSet resultset = statement.executeQuery(SQLSentence);

    return resultset;
  }
}
